package com.swxy.controller;

import com.swxy.pojo.User;
import com.swxy.pojo.admin;
import com.swxy.service.LoginService;
import com.swxy.service.adminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class CodeController {

    @Autowired
    LoginService userService;
    @Autowired
    adminService adminService;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(@RequestParam("phone") String phone,
                        @RequestParam("password") String password,
                        Model model, RedirectAttributes redirectAttributes) {

        User user = userService.login(phone, password);
        admin admins = adminService.adminLogin(phone, password);
        if (user != null) {
            // 登录成功，保存用户信息到Session中
            model.addAttribute("user", user);
            return "user";

        } else if (admins != null) {
            model.addAttribute("admins", admins);
            return "admin";

        } else {
            // 登录失败，返回登录页面并提示错误信息
            model.addAttribute("error", "用户名或密码错误");
//            redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
//            redirectAttributes.addFlashAttribute("timeout", 3);

            return "beaful";

        }

    }

//        @RequestMapping("/adminLogin")
//        public Object adminLogin (@RequestParam("phone") String phone, @RequestParam("password") String password, Model model){
//
//            admin res = adminService.adminLogin(phone,password);
//            if (res !=null) {
//                //登录成功
//                model.addAttribute("message", "登录成功！");
//                return "/jsp/user.jsp";
//            } else {
//                model.addAttribute("message", "用户名或密码错误，请重试！");
//                System.out.println(phone+password);
//                return "no";
//            }
//
//
//        }

    @RequestMapping("/register")
//    @ResponseBody
    public String register(User user) {
        User checkReg = userService.checkReg(user.getUserName());
        if (checkReg == null) {
            userService.addUser(user);
            return "beaful";
        }
        return "no";
    }

}



